package com.bishe.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import lombok.extern.slf4j.Slf4j;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class Sm2Util {

    /**
     * 获取公钥和私钥
     * @return
     */
    public static Map<String,String> getKey(){
        HashMap<String, String> map = new HashMap<>();
        KeyPair pair = SecureUtil.generateKeyPair("SM2");

        PrivateKey aPrivate = pair.getPrivate();
        map.put("privateKey",Base64.encode(aPrivate.getEncoded()));

        PublicKey aPublic = pair.getPublic();
        map.put("publicKey",Base64.encode(aPublic.getEncoded()));
        return map;
    }

    /**
     * 加密
     * @param key
     * @return
     */
    public static byte[] encryptBcd(byte[] bytes,String key){
        SM2 publicKey = SmUtil.sm2(null, key);
        return publicKey.encrypt(bytes, KeyType.PublicKey);
    }

    /**
     * 解密
     * @param key
     * @return
     */

    public static byte[]  decryptFromBcd(byte[] bytes,String key){
        key = key.replace(" ","+");
        SM2 privateKey = SmUtil.sm2(key, null);
        // 公钥加密，私钥解密
        return privateKey.decrypt(bytes, KeyType.PrivateKey);
    }


}
